package br.com.sigarota.bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.postgis.Point;

import br.com.sigarota.facade.PontoFacade;
import br.com.sigarota.facade.PontoFacadeImpl;
import br.com.sigarota.modelo.Ponto;

public class PontoBean implements Serializable {

	private static final long serialVersionUID = -333995781063775201L;

	private Ponto ponto = new Ponto();
	private String pointsMap = "";
	private List<Ponto> points = new ArrayList<Ponto>();
	private Long id;

	public PontoBean(){
		if(this.ponto == null){
			this.ponto = new Ponto(); 
		}

		try {
			//BufferedWriter out = new BufferedWriter(new FileWriter("/home/edilson/pontos_coordinates.txt")); 
			if(points.size() == 0){
				points = getPontos();
				for (Ponto p : points) {
					Point pp = (Point)p.getGeometry();
					pointsMap += p.getNome() + "#"+ pp.getX() + "#" + pp.getY() +"$";
					//pointsMap += "INSERT INTO PUBLIC.PONTO(DESCRICAO, GEOM) VALUES(\'" + p.getNome() + "\', GeomFromText('POINT("+ p.getGeometry().getX() + " " + p.getGeometry().getY() +")', -1))" + ";\n";
				}
			}
			//out.write(pointsMap);
			//out.close(); 
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	public String save(){
		PontoFacade PontoService = new PontoFacadeImpl();
		PontoService.salva(this.ponto);
		this.ponto = new Ponto(); 
		return "cadastraSucesso";
	}

	public String delete(){
		PontoFacade PontoService = new PontoFacadeImpl();
		this.ponto.setId(id);
		PontoService.remove(this.ponto);
		this.ponto = new Ponto(); 
		return "removeSucesso";
	}

	public String merge(){
		PontoFacade pontoService = new PontoFacadeImpl();
		pontoService.atualiza(this.ponto);
		this.ponto = new Ponto(); 
		return "atualizaSucesso";
	}

	public String load(){
		PontoFacade PontoService = new PontoFacadeImpl();
		this.ponto = PontoService.procura(this.id);
		return "pesquisaSucesso";
	}

	public String pesquisaByNome(){
		PontoFacadeImpl pontoService = new PontoFacadeImpl();
		this.ponto = pontoService.procuraByNome(this.ponto.getNome());
		return "pesquisaByNomeSucesso";
	}

	public List<Ponto> getPontos(){
		PontoFacade PontoService = new PontoFacadeImpl();		
		return PontoService.lista();
	}

	public List<Ponto> getPontosByNome(){ 
		PontoFacade PontoService = new PontoFacadeImpl();
		List<Ponto> lista = PontoService.pesquisaPontosByNome(this.ponto.getNome());
		return lista;
	}

	public Ponto getPonto() {
		return ponto;
	}

	public void setPonto(Ponto ponto) {
		this.ponto = ponto;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getPointsMap() {
		return pointsMap;
	}

	public void setPointsMap(String pointsMap) {
		this.pointsMap = pointsMap;
	}
}